<?php

namespace App\Listeners;

use App\Events\GameFinish;
use App\Models\ChildStar;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class AddPlayImages
{
    private $cache_head = "child_play";
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  GameFinish  $event
     * @return void
     */
    public function handle(GameFinish $event)
    {
        $tmp = $event->history;

        $key = cacheHead($this->cache_head). "_". $tmp->device->code."_images";
        $images = Cache::get($key, []);

        if (!empty($images)){
           $data = [];
           foreach ($images as $v){
              // 'child_id', 'device_id', 'game_id', 'history_id','image_path'
               $data[] = ['child_id'=>$tmp->child_id,
                   'device_id'=>$tmp->device_id,
                   'game_id'=>$tmp->game_id,
                   'history_id'=>$tmp->id,
                   'image'=>$v
               ];
           }
           $tmp->snapshots()->createMany($data);
           Cache::forget($key);

           Log::error("history save images success");
        }else{
           Log::error("history not have images ");
        }
    }
}
